import {
  store
} from "../../../store/store"
import {
  createStoreBindings
} from "mobx-miniprogram-bindings"
import {
  reqUploadFile,
  reqUploadUser
} from "../../../api/user"
import {
  setStorage,
  getStorage
} from "../../../utils/store"
Page({
  data: {
    isShowPopup: false // 控制更新用户昵称的弹框显示与否
  },
  onLoad() {
    this.storeBinding = createStoreBindings(this, {
      store,
      fields: ["userinfo", "token"],
      actions:["setUserInfo"]
    })
  },
  onUnload() {
    this.storeBinding.destroyStoreBindings()
  },
  // 获取用户头像信息
  async getAvatar(e) {
    // 获取用户临时路径
    const {
      avatarUrl
    } = e.detail
   
    console.log(e);
    // 头像临时路径 上传服务器
    const res = await reqUploadFile(avatarUrl, "file")
    this.setData({
      "userinfo.avatarUrl": res.data
    })
  },
  onUpdateNickName(e) {
    
    const {
      nickname
    } = e.detail.value
    this.setData({
      "userinfo.nickName": nickname,
      isShowPopup: false
    })
  },

  // 显示修改昵称弹框
  ShowPopup() {
    this.setData({
      isShowPopup: true
    })
  },
  cancel() {
    this.setData({
      isShowPopup: false
    })
  },
  // 保存按钮更新用户信息 
  async updateUser() {
    const {avatarUrl,nickName}= this.data.userinfo
    const params={
      nickname:nickName,
      headimgurl:avatarUrl
    }    
    const res = await reqUploadUser(params)
    if (res.code === 200) {
      wx.showToast({
        title: '保存' + res.message,
      })
      const data= this.data.userinfo
      // 修改本地
      setStorage("userinfo",data)
      // 修改仓库
      this.setUserInfo( data.avatarUrl,data.nickName)
      wx.navigateBack()
    }
  },

})